import React, { useState,useImperativeHandle,forwardRef,useContext,useEffect } from 'react';
import type { TabsProps,TableProps } from 'antd';
import { Tabs,Table,Pagination,Drawer } from 'antd';
import { DownOutlined } from '@ant-design/icons';
import { WorkbenchesContext, } from '@/components/workbenches/workbenches-context';

type TargetKey = React.MouseEvent | React.KeyboardEvent | string;

interface RecordType {
    id: number;
    firstName: string;
    lastName: string;
    age: number;
    address1: string;
    address2: string;
    address3: string;
}

const App = forwardRef(({ open,onClose,executeName },ref) => {

    const [activeKey, setActiveKey] = useState('1');

    function organizeData(list:any) {
        if (!Array.isArray(list) || list.length === 0) {
          return []
        }
        // 提取表头
        const headers = Object.keys(list[0]);
        return headers
    }
      

    // 向父组件暴露方法
    useImperativeHandle(ref, () => ({
        onEdit: onEdit
    }));

    const pagination = {
        current:10000,
        pageSize:1000,
        pageNo:1
    }
    const [items, setItems] = useState<TabsProps['items']>([]);
    const [node, setNode] = useState({});

    const add = (headerList:[],list:[]) => {
        const newKey = String((items || []).length + 1);
        const columns: TableProps<RecordType>['columns'] = [
            {
                title: '',
                key: 'index',
                dataIndex: 'index', // 可省略，仅用于数据绑定
                render: (_, __, index) => (
                  <span style={{ fontWeight: 'bold' }}>
                    { index + 1 }
                  </span>
                ),
                width: 80,
                align: 'center',
                fixed: 'left', // 固定首列 
            },
        ];
        headerList.forEach((item: any) => {
            columns.push({
                title: item,
                dataIndex: item,
                width: 140,
            });
        })
        setItems([
        ...(items || []),
        {
            label: `结果 ${newKey}`,
            key: newKey,
            children: (
                <div>
                    {/* <Pagination className='my-2' defaultCurrent={pagination.pageNo} total={pagination.current} pageSize={pagination.pageSize} /> */}
                    <Table
                        columns={[...columns]}
                        virtual
                        scroll={{ x: 100, y: 260 }}
                        pagination={false}
                        dataSource={list}
                        showSorterTooltip={{ target: 'sorter-icon' }}
                    />
                    <div className='mt-2 flex justify-between items-center'>
                        <div>执行完成  耗时17ms</div>
                        <div>{executeName}</div>
                    </div>
                </div>
            ),
        },
        ]);
        setActiveKey(newKey);
    };

    const remove = (targetKey: TargetKey) => {
        if (!items) return;
        const targetIndex = items.findIndex((item) => item.key === targetKey);
        const newItems = items.filter((item) => item.key !== targetKey);

        if (newItems.length && targetKey === activeKey) {
        const newActiveKey =
            newItems[targetIndex === newItems.length ? targetIndex - 1 : targetIndex].key;
        setActiveKey(newActiveKey);
        }

        setItems(newItems);
    };

    const onEdit = (targetKey: TargetKey, action: 'add' | 'remove', params:[]) => {
        if (action === 'add') {
            if (params) {
                let headerList = organizeData(params);
                console.log(headerList, 'headerList');
                add(headerList,params);
            }
            // const newTab = {
            //     label: `Tab ${items?.length}`,
            //     key: items?.length,
            //     children: (
            //         <div>
            //             {/* 这里可以添加新的内容，类似于第一个 Tab */}
            //             <Pagination className='my-2' defaultCurrent={pagination.pageNo} total={pagination.current} pageSize={pagination.pageSize} />
            //             <Table
            //                 columns={[...columns]}
            //                 virtual
            //                 scroll={{ x: 100, y: 240 }}
            //                 pagination={false}
            //                 dataSource={data}
            //                 showSorterTooltip={{ target: 'sorter-icon' }}
            //             />
            //             <div className='mt-2 flex justify-between items-center'>
            //                 <div>执行完成  耗时17ms</div>
            //                 <div>@192.168.6.45/customer</div>
            //             </div>
            //         </div>
            //     ),
            // };
    
           
        } else {
            remove(targetKey);
        }

    };
    return (
        <div style={{position: 'relative',}}>
            <Drawer
                bodyStyle={{ padding: 0 }}
                title=""
                style={{ position: 'absolute' }}
                placement='bottom'
                closable={false}
                onClose={() => onClose(false)}
                height={'460px'}
                width={'600px'}
                open={open}
                mask={false}
                getContainer={false}
            >
                <div className='flex justify-end items-center p-2 mr-2'>
                    <DownOutlined className='ml-2' onClick={() => onClose(false)} />
                </div>
                <Tabs
                    className='mt-2 ml-2'
                    type="editable-card"
                    activeKey={activeKey}
                    onChange={setActiveKey}
                    onEdit={onEdit}
                    size={'small'}
                    items={items}
                    hideAdd={true}
                >
                </Tabs>
            </Drawer>
        </div>
    );
});

export default App;